#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/14  13:13
# @Author: 余浪人
# @email: yulangren520@gmail.com
from flask_login import current_user
from wtforms import Form, StringField, validators, PasswordField, SelectField

from apps.models.admin_model import Admin_Model, Authority_Model


class Admin_Form(Form):
    def __init__(self, *args, **kwargs):
        super(Admin_Form, self).__init__(*args, **kwargs)
        self.authority.choices = [(r.id, r.authority_name) for r in Authority_Model.query.all()]  # 初始化权限

    username = StringField(
        '登录名', validators=[validators.DataRequired('登录名不可为空!'), validators.Length(2, message='登录名长度不足!')],
        render_kw={"lay-verify": "nikename", "required": "", "class": "layui-input", "style": "width: 60%;"})
    password = PasswordField(
        label=u'密码', validators=[validators.Length(min=6, message='密码至少6位!')],
        render_kw={"required": "", "class": "layui-input", "style": "width: 60%;"})
    password2 = PasswordField(
        label=u'确认密码', validators=[validators.EqualTo('password', '两次密码不一致!')],
        render_kw={"required": "", "class": "layui-input", "style": "width: 60%;"})
    remark = StringField('备注信息', render_kw={"class": "layui-input", "style": "width: 60%;"})
    authority = SelectField('权限', validators=[validators.DataRequired('请选择权限!')], coerce=int)

    def validate_username(self, username):
        cou = Admin_Model.query.filter(Admin_Model.username == username.data)
        if cou.count() and cou.first().id != current_user.id:
            raise validators.ValidationError("此登录名已存在!")


class Admin_Edit_Form(Form):
    username = StringField(
        '登录名', validators=[validators.DataRequired('登录名不可为空!'), validators.Length(2, message='登录名长度不足!')],
        render_kw={"lay-verify": "nikename", "required": "", "class": "layui-input", "style": "width: 60%;"})
    password = PasswordField(
        label=u'密码', validators=[validators.Length(min=6, message='密码至少6位!')],
        render_kw={"required": "", "class": "layui-input", "style": "width: 60%;"})
    password2 = PasswordField(
        label=u'确认密码', validators=[validators.EqualTo('password', '两次密码不一致!')],
        render_kw={"required": "", "class": "layui-input", "style": "width: 60%;"})

    # remark = StringField('备注信息', render_kw={"class": "layui-input", "style": "width: 60%;"})

    def validate_username(self, username):
        cou = Admin_Model.query.filter(Admin_Model.username == username.data)
        if cou.count() and cou.first().id != current_user.id:
            raise validators.ValidationError("此登录名已存在!")


class Login_Form(Form):
    username = StringField('登录名', validators=[validators.DataRequired('帐号不可为空!')])
    password = StringField('密码', validators=[validators.DataRequired('密码不可为空!')])

    def validate_username(self, username):
        cou = Admin_Model.query.filter(Admin_Model.username == username.data).count()
        if cou == 0:
            raise validators.ValidationError("账号不存在!")
